package com.ns.school.common.base;

import com.ns.school.common.utils.JsonUtil;

import java.io.Serializable;

/**
 * 接口统一返回对象
 *
 * @author Spark
 */
public class R<T> implements Serializable {

    private static final long serialVersionUID = 1L;
    private static final String ERROR_001 = "DataLenOut";

    private int count = 0;
    private int code = 0;      // 0成功;-1:登录失效;>0错误
    private String msg = "";

    private T data;         // 主数据-如果是列表数据,则必须为集合list类型
    private Object remark;  // 备选数据

    public R() {
    }

    public R(int code, String msg) {
        this.code = code;
        this.msg = msg;
    }

    public R(T data) {
        this.data = data;
    }

    public R(T data, int count) {
        this.data = data;
        this.count = count;
    }

    public R(T data, long count) {
        this.data = data;
        this.count = (int) count;
    }

    public static <T> R<T> success() {
        return new R<>();
    }

    public static <T> R<T> success(T data, String message) {
        R<T> dataGrid = new R<>(data);
        dataGrid.setMsg(message);
        return dataGrid;
    }

    public static <T> R<T> error(String message) {
        if (message == null || message.length() > 500) {
            message = ERROR_001;
        }
        return new R<>(599, message);
    }

    public static <T> R<T> error(Integer code, String message) {
        return new R<>(code, message);
    }

    public static <T> R<T> success(String message) {
        R<T> dg = new R<>();
        dg.setMsg(message);
        return dg;
    }

    public static <T> R<T> success(T data) {
        return new R<>(data);
    }

    public static <T> R<T> success(T data, long count) {
        return new R<>(data, count);
    }

    public static <T> R<T> failed(int code, String msg) {
        return new R<>(code, msg);
    }

    public boolean isSuccess() {
        return this.code == 0;
    }

    public int getCount() {
        return count;
    }

    public void setCount(int count) {
        this.count = count;
    }

    public void setCount(long count) {
        this.count = (int) count;
    }

    public int getCode() {
        return code;
    }

    public void setCode(int code) {
        this.code = code;
    }

    public String getMsg() {
        return msg;
    }

    public void setMsg(String msg) {
        this.msg = msg;
    }

    public T getData() {
        return data;
    }

    public void setData(T data) {
        this.data = data;
    }

    public Object getRemark() {
        return remark;
    }

    public void setRemark(Object remark) {
        this.remark = remark;
    }

    @Override
    public String toString() {
        return JsonUtil.toStr(this);
    }
}
